<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <title>踩高跷</title>
</head>

<body>
    <style>
        * {
            margin: 0;
            padding: 0;
            -webkit-touch-callout: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
        }

        #demo-quickStart {
            width: 100%;
            height: 100vh;
        }

        .bamboo {
            transform: rotate(-80deg);
        }

        .mask-box {
            position: fixed;
            width: 100%;
            height: 100vh;
            z-index: 99;
            top: 0;
            left: 0;
            display: flex;
            background: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }

        .wrap {
            display: flex;
            width: 50%;
            flex-direction: column;
            color: antiquewhite;
            justify-content: center;
        }

        .wrap p {
            margin-bottom: 30px;
            text-align: center;
        }

        .start {
            width: 37%;
        }

        button {
            padding: 10px;
        }

        .ground {
            padding: 0 40px;
        }

        video {
            display: none;
        }

        .loading-box {
            position: fixed;
            width: 100vw;
            height: 100vh;
            top: 0;
            left: 0;
            background: rgba(255, 255, 255, 0.7);
            z-index: 99;

        }

        .loading-box img {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 50%;
            transform: translate(-50%, -50%);
        }

        .score-box {
            position: fixed;
            top: 30px;
            left: 30px;
            display: flex;
            width: 100%;
            font-size: 16px;
        }

        .score-box div {
            min-width: 105px;
            padding: 2px 5px;
            border: 3px solid #fff;
            border-radius: 8px;
            margin-right: 20px;
            background: rgba(255, 255, 255, 0.3);
        }

        .score-box span {
            font-size: 22px;
            -webkit-text-fill-color: red;
            -webkit-text-stroke-color: white;
            -webkit-text-stroke-width: 1px;
            font-weight: bold;
        }
    </style>
    <div class="loading-box">
        <img src="./img/loading.gif" alt="">
    </div>
    <div id="demo-quickStart"></div>
    <div class="score-box">
        <div>得分：<span class="score">0</span></div>
        <div>倒计时：<span class="timer">60s</span>
        </div>
    </div>
    <div class="mask-box">
        <div class="wrap">
            <p>点击屏幕,人物跳跃</p>
        </div>
        <img src="./img/game1_6.png" alt="" class="start">
    </div>
    <video src="./images/222.mp3" autoplay></video>
    <script src="./js/sprite.js"></script>
    <script src="./js/jquery.js"></script>
    <script src="https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script src="./js/request.js"></script>
    <script>
        request('get_share_sign/', {
            zm_token: localStorage.user_token,
            _zm_post_type: 'ajax',
            url: location.href
        }).then(res => {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: res.rsm.appId, // 必填，公众号的唯一标识
                timestamp: res.rsm.timestamp, // 必填，生成签名的时间戳
                nonceStr: res.rsm.nonceStr, // 必填，生成签名的随机串
                signature: res.rsm.signature, // 必填，签名
                jsApiList: ['onMenuShareTimeline',
                    'onMenuShareAppMessage',
                    'onMenuShareQQ',
                    'onMenuShareWeibo',
                    'onMenuShareQZone',
                    'onMenuShareTimeline',
                    'updateAppMessageShareData',
                    'hideOptionMenu',
                    'showOptionMenu',
                    'hideMenuItems',
                    'showMenuItems',
                    'hideAllNonBaseMenuItem',
                    'showAllNonBaseMenuItem',
                ] // 必填，需要使用的JS接口列表
            });
            wx.ready(function () { //需在用户可能点击分享按钮前就先调用
                wx.hideAllNonBaseMenuItem();
            });
        })
        let gameNumber = Number(JSON.parse(localStorage.getItem('game2')).number)
        if (gameNumber == 0) {
            $('.mask-box').hide()
            let loadingTimer = setTimeout(() => {
                $('.mask-box').show()
                $('.loading-box').hide()
                clearTimeout(loadingTimer)
                let obj = JSON.parse(localStorage.getItem('game2'))
                obj.number = 1
                gameNumber = 1
                localStorage.setItem('game2', JSON.stringify(obj))
            }, 5000)
        } else {
            $('.loading-box').hide()
        }

        const {
            Scene,
            Sprite,
            Label,
            Group
        } = spritejs;
        const scene = new Scene('#demo-quickStart', {
            viewport: ['auto', 'auto'],
            resolution: [750, 1334],
            useDocumentCSS: true,
        });
        const layer = scene.layer();
        const bgImg1 = new Sprite('http://qrwbtqqjh.hn-bkt.clouddn.com/game4_bg.jpg')
        const bgImg2 = new Sprite('http://qrwbtqqjh.hn-bkt.clouddn.com/game4_bg.jpg')
        const ground1 = new Sprite('./img/ground1.png')
        const ground2 = new Sprite('./img/ground2.png')
        const ground3 = new Sprite('./img/ground3.png')
        const coin = new Sprite('./img/coin_icon.png')
        const boy = new Sprite('./img/20.png')
        const label = new Label('得分:')
        const label2 = new Label('倒计时:')
        const times = new Label('60')
        const score = new Label('0')
        let list = [
            './img/monster3.png',
            './img/monster4.png',
            './img/monster41.png',
            './img/monster5.png',
            './img/monster6.png',
            './img/monster9.png'
        ]

        let speed = 6000 //初始速度
        let trd, mtrd, monster



        bgImg1.attr({
            size: [3369, 1334],
            pos: [0, 0]
        })
        bgImg2.attr({
            size: [3369, 1334],
            pos: [3369, 0]
        })

        coin.attr({
            size: [60, 60],
            borderRaiud: '50%'
        })

        const bgAmin1 = bgImg1.animate([{
            x: -3369
        }], {
            duration: 20000,
            iterations: Infinity,
            easing: 'linear'
        })
        const bgAmin2 = bgImg2.animate([{
            x: 0
        }], {
            duration: 20000,
            iterations: Infinity,
            easing: 'linear'
        })

        boy.attr({
            anchor: 0.5,
            size: [200, 350],
            pos: [375, 970],
            // bgcolor: 'red'
        })

        label.attr({
            anchor: 0.5,
            fillColor: '#000',
            font: '24px "微软雅黑"',
            pos: [150, 100],
        })

        label2.attr({
            anchor: 0.5,
            fillColor: '#000',
            font: '24px "微软雅黑"',
            pos: [300, 100],
        })

        score.attr({
            anchor: 0.5,
            fillColor: '#000',
            font: '24px "微软雅黑"',
            pos: [200, 102],
        })

        times.attr({
            anchor: 0.5,
            fillColor: '#000',
            font: '24px "微软雅黑"',
            pos: [380, 102],
        })

        boy.animate([{
                textures: './img/23.png'
            },
            {
                textures: './img/22.png'
            },
            {
                textures: './img/21.png'
            },
            {
                textures: './img/20.png'
            },
        ], {
            duration: 500,
            iterations: Infinity,
            easing: 'step-end',
        })

        ground1.attr({
            pos: [0, 1134],
            size: [480, 400],
            // class: 'ground'
        })

        ground2.attr({
            pos: [750, 1034],
            size: [480, 400],
            // class: 'ground'
        })
        ground3.attr({
            pos: [1500, 1134],
            size: [480, 400],
            // class: 'ground'
        })
        const groundAnim1 = ground1.animate([{
            x: -1500
        }], {
            duration: speed,
            iterations: Infinity,
            easing: 'linear'
        })

        const groundAnim2 = ground2.animate([{
            x: -750
        }], {
            duration: speed,
            iterations: Infinity,
            easing: 'linear'
        })

        const groundAnim3 = ground3.animate([{
            x: 0
        }], {
            duration: speed,
            iterations: Infinity,
            easing: 'linear'
        })

        layer.append(bgImg1, bgImg2, boy, ground1, ground2, ground3)



        // 河流和路面速度
        // let boySpeed = 3200
        // let groundTimer = setInterval(() => {
        //     // speed -= 100
        //     boySpeed -= 100
        //     groundAnim1.timeline.playbackRate += 0.1
        //     groundAnim2.timeline.playbackRate += 0.1
        //     groundAnim3.timeline.playbackRate += 0.1
        //     // bgAmin1.timeline.playbackRate += 0.1
        //     // bgAmin2.timeline.playbackRate += 0.1

        //     if (speed == 1000) {
        //         clearInterval(groundTimer)
        //     }
        // }, 4000)

        layer.timeline.playbackRate = 0

        $('.start').click(function () {
            request('begin_jump/', {
                zm_token: localStorage.user_token,
                _zm_post_type: 'ajax'
            }).then(res => {
                console.log(res.rsm);
            })
            $('.mask-box').hide()
            $(this).hide()
            score.attributes.text = 0
            layer.timeline.playbackRate = 1
            timer()
            collision()

            let coinTimer = setInterval(() => {
                addCoinRandom()
            }, 3000)

            let monTimer = setInterval(() => {
                addMonsterRandom()
            }, 10000);
        })

        // 页面倒计时
        let pageTimer, pTime = 60

        function timer() {
            pageTimer = setInterval(() => {
                pTime--
                times.attributes.text = `${pTime}`
                $('.timer').text(`${pTime}s`)
                if (pTime == 0) {
                    clearInterval(pageTimer)
                    request('end_jump/', {
                        zm_token: localStorage.user_token,
                        _zm_post_type: 'ajax',
                        jump_score: score.attributes.text
                    })
                    $('.wrap p').text(`游戏结束, 得分${score.attributes.text}`)
                    $('button').hide()
                    $('.mask-box').show()
                    layer.timeline.playbackRate = 0
                    let game = locMemory.localStorage.getItem(`game2`)
                    let gameScore = game.score
                    let gameState = game.active
                    let gameLuck = game.luck
                    let obj = {
                        score: (score.attributes.text | 0) > gameScore ? score.attributes.text : gameScore,
                        active: gameState ? gameState : ((score.attributes.text | 0) >= (locMemory
                            .localStorage.getItem(
                                'gameScore').jump_score | 0)),
                        luck: game.luck,
                        number: game.number
                    }
                    obj = JSON.stringify(obj)
                    localStorage.setItem(`game2`, obj)
                    setTimeout(() => {
                        location.href = `gameState.html?score=${score.attributes.text}`
                    }, 2000)
                }
            }, 1000)
        }

        let end = true //跳跃动作是否结束
        let jumState = 1 //1 第二个路面  2第一和三路面
        let timeStart = 0,
            timeEnd, timeEvent //判断按键时长
        layer.on('touchstart', (e) => {
            e.preventDefault();
            timeEvent = setInterval(() => {
                timeStart++
            }, 100);
            // console.log(timeEvent);
            return false
        })

        layer.on('touchend', (e) => {
            e.preventDefault()
            clearInterval(timeEvent)
            jump(timeStart > 2 ? 500 : 700)
            timeStart = 0
            return false
        })


        // 随机出现金币
        async function addCoinRandom() {
            let rd = 700 + Math.round(Math.random() * 100) //金币随机高度
            coin.attr({
                pos: [750, rd]
            })
            layer.append(coin)
            const coinAnim = await coin.animate([{
                x: -900
            }], {
                duration: 3000,
                iterations: Infinity,
                easing: 'linear'
            })
            coinAnim.finished.then(() => {
                layer.remove(coin)
            })
        }

        // 随机出现怪物
        async function addMonsterRandom() {
            let mra = Math.round(Math.random() * 4)
            let hra = Math.round(Math.random() * 720)

            monster = new Sprite(`${list[mra]}`)
            await monster.attr({
                pos: [750, hra],
                size: [70, 90],
                borderRadius: 40,
                // bgcolor: 'red'
            })
            layer.append(monster)
            const monsterAnim = await monster.animate([{
                x: -900
            }], {
                duration: 3000,
                easing: 'linear'
            })
            monsterAnim.finished.then(() => {
                layer.remove(monster)
            })
        }

        // 跳动
        async function jump(y) {
            if (end) {
                end = false
                let jumpTimer = setTimeout(() => {
                    end = true
                    clearTimeout(jumpTimer)
                }, 2800)
                console.log(y);
                await boy.transition(0.4).attr({
                    pos: [375, y],
                })
                await boy.transition(0.4).attr({
                    pos: [375, jumState == 1 ? 970 : 870],
                })
                score.attributes.text = `${Number(score.attributes.text) + 1}`
                $('.score').text(`${Number(score.attributes.text)}`)
            }
        }

        // 随机生成河流
        async function addRandomRiver() {
            ground1.attr({
                pos: [0, 1134],
                size: [550, 200],
                // class: 'ground'
            })

            ground2.attr({
                pos: [750, 1134],
                size: [550, 200],
                // class: 'ground'
            })
            ground3.attr({
                pos: [1500, 1134],
                size: [550, 200],
                // class: 'ground'
            })
            const groundAnim1 = ground1.animate([{
                x: -2250
            }], {
                duration: speed,
                iterations: Infinity,
                easing: 'linear'
            })

            const groundAnim2 = ground2.animate([{
                x: -1500
            }], {
                duration: speed,
                iterations: Infinity,
                easing: 'linear'
            })

            const groundAnim3 = ground3.animate([{
                x: -750
            }], {
                duration: speed,
                iterations: Infinity,
                easing: 'linear'
            })
            groundAnim1.finished.then(() => {
                ground1.remove()
            })
            groundAnim2.finished.then(() => {
                ground2.remove()
            })
            groundAnim3.finished.then(() => {
                ground3.remove()
            })
            layer.append(ground1, ground2, ground3)
        }


        //  碰撞检测
        function collision() {
            layer.on('update', (env) => {
                if (boy.OBBCollision(coin)) {
                    layer.remove(coin)
                    score.attributes.text = `${Number(score.attributes.text) + 1}`
                    $('.score').text(`${Number(score.attributes.text)}`)
                }

                if (monster) {
                    if (boy.OBBCollision(monster)) {
                        layer.remove(monster)
                        gameOver()
                    }
                }

                // 碰到坑 游戏结束
                if (end) {
                    if (boy.OBBCollision(ground1) || boy.OBBCollision(ground3)) {
                        boy.attr({
                            pos: [375, 970]
                        })
                        jumState = 1
                        return
                    } else if (boy.OBBCollision(ground2)) {
                        boy.attr({
                            pos: [375, 870]
                        })
                        jumState = 2
                        return
                    } else {
                        console.log('跳跃结束未在地面');
                        boy.attr({
                            pos: [375, 1060],
                        })
                        gameOver()
                        return
                    }
                } else {
                    if (boy.OBBCollision(ground1) || boy.OBBCollision(ground3)) {
                        jumState = 2
                    }
                    if (boy.OBBCollision(ground2)) {
                        jumState = 1
                        return
                    }
                }
            })
        }


        // 游戏结束
        function gameOver() {
            layer.timeline.playbackRate = 0
            clearInterval(pageTimer)
            request('end_jump/', {
                zm_token: localStorage.user_token,
                _zm_post_type: 'ajax',
                jump_score: score.attributes.text
            })
            $('.wrap p').text(`游戏结束, 得分${score.attributes.text}`)
            $('button').hide()
            $('.mask-box').show()
            // 记得清除
            let game = locMemory.localStorage.getItem(`game2`)
            let gameScore = game.score | 0
            let gameState = game.active
            let gameLuck = game.luck
            let obj = {
                score: (score.attributes.text | 0) > gameScore ? score.attributes.text : gameScore,
                active: gameState ? gameState : ((score.attributes.text | 0) >= (locMemory.localStorage.getItem(
                    'gameScore').jump_score | 0)),
                luck: game.luck,
                number: game.number
            }
            obj = JSON.stringify(obj)
            localStorage.setItem(`game${localStorage.getItem('progress')}`, obj)
            // -------------------------
            setTimeout(() => {
                location.href = `gameState.html?score=${score.attributes.text}`
            }, 2000)
        }
    </script>
</body>

</html>